/**
 * 
 */
package edu.rice.test;

import java.util.Random;

import javax.swing.JFrame;
import edu.rice.myxo.utils.*;

/**
 * @author frogy
 * 
 */
public class newAlgo {

	private static double segLength = 1;

	private static double L = 100;

	private static int segNum = 50;

	private static void moveSeg(int segID, double[] x, double[] xn) {
		double[] d = new double[2];
		for (int i = 0; i < d.length; i++) {
			d[i] = Math.abs(x[segID] - xn[2 * segID + i]);
		}
		if ((d[0] <= segLength && d[1] > segLength)) {
			x[segID] += min(Math.abs(d[1] - segLength), segLength);

		}
		if ((d[1] <= segLength && d[0] > segLength)) {
			x[segID] -= min(Math.abs(d[0] - segLength), segLength);

		}
	}

	private static double[] findSegNeighbor(int segID, double[] x) {
		double[] xn = new double[2];
		xn[0] = 0;
		xn[1] = L;
		for (int i = 0; i < x.length; i++) {
			if (x[i] > xn[0] && x[i] < x[segID]) {
				xn[0] = x[i];
			}
			if (x[i] > x[segID] && x[i] < xn[1]) {
				xn[1] = x[i];
			}
		}
		return xn;
	}

	private static double[] findSegNeighbor(double[] x) {
		double[] xn = new double[2 * segNum];
		for (int i = 0; i < segNum; i++) {
			double[] tempxn = findSegNeighbor(i, x);
			xn[2 * i] = tempxn[0];
			xn[2 * i + 1] = tempxn[1];
		}
		return xn;
	}

	private static double min(double a, double b) {
		return a < b ? a : b;
	}

	public static void main(String[] args) {
		
		long timeStart = System.currentTimeMillis();
		Random r = new Random();
		r.setSeed(123456789);
		double[] x = new double[segNum];
		double[] xini = new double[segNum];
		double[] xn = new double[2 * segNum];
		for (int i = 0; i < segNum; i++) {
			x[i] = r.nextDouble() * L;
			xini[i] = x[i];
		}
		xn = findSegNeighbor(x);
		while (true) {
			boolean overlap = false;
			for (int i = 0; i < segNum; i++) {
				if (x[i] - xn[2 * i] <= segLength
						|| xn[2 * i + 1] - x[i] <= segLength) {
					overlap = true;
					moveSeg(i, x, xn);
				}
			}
			xn = findSegNeighbor(x);
			if (!overlap) {
				break;
			}

		}
		double chAve = 0;
		double chMax = 0;
		double chMin = 100;
		int numMoved = 0;
		for (int i = 0; i < segNum; i++) {
			double ch = Math.abs(x[i] - xini[i]);
			if (ch > 0) {
				numMoved++;
				if (ch > chMax) {
					chMax = ch;
				}
				if (ch < chMin) {
					chMin = ch;
				}
			}
			chAve += ch;
		}
		chAve /= (double) numMoved;
		System.out.println("On average, each moved cell moved " + chAve + ".");
		System.out.println("Max displacement is " + chMax + ".");
		System.out.println("Min displacement is " + chMin + ".");
		PaintIMs pm = new PaintIMs();
		pm.getParam(segNum, segLength, x, xini);
		pm.saveImage("aa.png");
		long timeEnd = System.currentTimeMillis();
		System.out.println("total time: " + (timeEnd - timeStart));
	}
}
